package com.example.utils;

import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

/**
 * 为asr的websocket报错解决提供不足的工具
 */
public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 将对象转换为JSON字符串
    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON序列化失败", e);
        }
    }

    // 将JSON字符串解析为JsonNode
    public static JsonNode parse(String json) {
        try {
            return objectMapper.readTree(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }

    // 将JSON字符串转换为Map
    public static Map<String, Object> toMap(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON转换为Map失败", e);
        }
    }

    // 将JSON字符串转换为JSONObject
    public static JSONObject toJSONObject(String json) {
        try {
            return new JSONObject(json);
        } catch (Exception e) {
            throw new RuntimeException("JSON转换为JSONObject失败", e);
        }
    }

    // 将JSON字符串转换为Map<String, String>
    public static Map<String, String> toStringMap(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON转换为Map<String, String>失败", e);
        }
    }
}